package com.mvc.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.config.ActionForward;
import com.mvc.config.ConfigBean;
import com.mvc.form.ActionForm;

public class ActionServlet extends HttpServlet{

	private static final long serialVersionUID = 4502249532149402531L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String actionName = getAction(req.getServletPath());
		String methodName = getMethod(req.getServletPath());
		Map<String, ConfigBean> mvcConfig = (Map<String, ConfigBean>) req.getSession().getServletContext().getAttribute("mvcConfig");
		
		ConfigBean configBean = mvcConfig.get(actionName);
		
		String formBeanName = configBean.getForm();
		ActionForm form = ActionForm.getFormData(formBeanName, req);

		Class<?> actionClass = configBean.getActionClass();
		//调用具体的方法
		String result = Action.getResult(actionClass, methodName, req, resp, form);
		
		Map<String, ActionForward> fMap = configBean.getMethod().get(methodName);
		
		ActionForward forward = fMap.get(result);
		
		req.getRequestDispatcher(forward.getResultUrl()).forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req,resp);
	}

	@Override
	public void service(ServletRequest req, ServletResponse res)
			throws ServletException, IOException {
		super.service(req, res);
	}
	
	public String getAction(String servletPaht){
		return servletPaht.substring(0,servletPaht.lastIndexOf("/"));
	}
	
	public String getMethod(String servletPaht){
		return servletPaht.substring(servletPaht.lastIndexOf("/") + 1);
	}

}
